package ch.exm.storm.collections;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BoundedFifoMap<K, V> extends HashMap<K, V> {

	private static final long serialVersionUID = 1L;

	private static final int DEFAULT_SIZE = 32;
	
	private int size;
	private List<K> fifoEntryList;
	
	public BoundedFifoMap() {
		this(DEFAULT_SIZE);
	}
	
	public BoundedFifoMap(int size) {
		this.size = size;
		fifoEntryList = new ArrayList<K>(size);
	}
	
	@Override
	public void clear() {
		super.clear();
		fifoEntryList.clear();
	}

	@Override
	public V put(K key, V value) {
		if (containsKey(key)) remove(key);
		else if (fifoEntryList.size() >= size) remove(fifoEntryList.remove(size-1));
		fifoEntryList.add(0, key);
		return super.put(key, value);
	}

	@Override
	public void putAll(Map<? extends K, ? extends V> map) {
		for (K key : map.keySet()) super.put(key, map.get(key));
	}

	@Override
	public V remove(Object key) {
		fifoEntryList.remove(key);
		return super.remove(key);
	}
}
